<html lang="en-US">

<head>
    
<title>Go 读者提问：值为 nil 也能调用函数，太神奇了吧？ - 花落雨忧</title>

<meta property="og:title" content="Go 读者提问：值为 nil 也能调用函数，太神奇了吧？ - 花落雨忧">



    



    
    <meta property="description" content="大家好，我是煎鱼。
最近在我们 Go 的技术交流群里，有一个小伙伴提了一个程序方面的问题，还挺有意思的，分享给大家。
[&amp;hellip;] 示例程序如下：
[&amp;hellip;] type T struct{} func (t *T) Hello() string { if t == nil { fmt.Println(&amp;#34;脑子进煎鱼了&amp;#34;) return &amp;#34;&amp;#34; } &amp;hellip;">
    <meta property="og:description" content="大家好，我是煎鱼。
最近在我们 Go 的技术交流群里，有一个小伙伴提了一个程序方面的问题，还挺有意思的，分享给大家。
[&amp;hellip;] 示例程序如下：
[&amp;hellip;] type T struct{} func (t *T) Hello() string { if t == nil { fmt.Println(&amp;#34;脑子进煎鱼了&amp;#34;) return &amp;#34;&amp;#34; } &amp;hellip;">
    






<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width,initial-scale=1">

<link rel="shortcut icon" href="https://www.lican.site/logo/logo.png" type="image/x-icon" />



<link rel="stylesheet" href="/css/style.min.css" />

<link rel="stylesheet" href="/css/reset.min.css" />




<script src="https://www.lican.site/js/highlight.min.js"></script>

<script>
hljs.configure({ ignoreUnescapedHTML: true })
hljs.highlightAll();
</script>


<script src="https://www.lican.site/js/jquery.min.js"></script>




<link href="https://www.lican.site/css/hugo-code.min.css" rel="stylesheet" />



    <style>
        .post-content img {
            max-width: 400px;
        }
    </style>
</head>

<body id="period" class="home blog">
    <a class="skip-content" href="#main">Press "Enter" to skip to content</a>
    <div id="overflow-container" class="overflow-container">
        <header class="site-header" id="site-header" role="banner">
    <div class="max-width">
        <div id="title-container" class="title-container">
            <div id="site-title" class="site-title"><a href="/">花落雨忧</a></div>
            <p class="tagline">思所及 力所行 方为真.</p>
        </div>
        
        <div id="menu-primary-container" class="menu-primary-container">
            <div class="icon-container">
            </div>
            <div id="menu-primary" class="menu-container menu-primary" role="navigation">
                <nav class="menu">
                    <ul id="menu-primary-items" class="menu-primary-items">
                        
                        
                        <li id="menu-item-0"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/posts" aria-current="page" tabindex="0">首页</a></li>
                        
                        <li id="menu-item-1"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/tech/" aria-current="page" tabindex="1">技术文档</a></li>
                        
                        <li id="menu-item-2"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/article/" aria-current="page" tabindex="2">文章</a></li>
                        
                        <li id="menu-item-3"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/project/" aria-current="page" tabindex="3">项目</a></li>
                        
                        <li id="menu-item-4"
                            class="menu-item menu-item-type-custom menu-item-object-custom ">
                            <a href="/about/" aria-current="page" tabindex="4">关于</a></li>
                        
                    </ul>
                </nav>
            </div>
        </div>
    </div>
</header>
        <div id="primary-container" class="primary-container">
            <div class="max-width">
                <section id="main" class="main" role="main">
                    <div id="loop-container" class="loop-container">
                        <div
                            class="post type-post status-publish format-standard hentry entry">
                            <article>
                                <div class="post-container">
                                    <div class="post-header">
                                        <h2 class="post-title">
                                            <a href="/posts/go/nil-func/">Go 读者提问：值为 nil 也能调用函数，太神奇了吧？</a>
                                        </h2>
                                        
                                        <div class="post-byline">Published on
                                            <a class="date" href="javascript:;">2021/12/31</a>
                                            
                                            
                                            
                                            
                                            
                                        
                                    </div>
                                    <div class="post-content">
                                        <p>大家好，我是煎鱼。</p>
<p>最近在我们 Go 的技术交流群里，有一个小伙伴提了一个程序方面的问题，还挺有意思的，分享给大家。</p>
<p><img src="https://files.mdnice.com/user/3610/0774f643-81a2-4458-b557-05c81a9572ef.png" alt=""></p>
<h2 id="示例">示例</h2>
<p>示例程序如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">type</span> <span style="color:#a6e22e">T</span> <span style="color:#66d9ef">struct</span>{}

<span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">t</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">T</span>) <span style="color:#a6e22e">Hello</span>() <span style="color:#66d9ef">string</span> {
	<span style="color:#66d9ef">if</span> <span style="color:#a6e22e">t</span> <span style="color:#f92672">==</span> <span style="color:#66d9ef">nil</span> {
		<span style="color:#a6e22e">fmt</span>.<span style="color:#a6e22e">Println</span>(<span style="color:#e6db74">&#34;脑子进煎鱼了&#34;</span>)
		<span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;&#34;</span>
	}

	<span style="color:#66d9ef">return</span> <span style="color:#e6db74">&#34;煎鱼进脑子了&#34;</span>
}

<span style="color:#66d9ef">func</span> <span style="color:#a6e22e">main</span>() {
	<span style="color:#66d9ef">var</span> <span style="color:#a6e22e">t</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">T</span>
	<span style="color:#a6e22e">t</span>.<span style="color:#a6e22e">Hello</span>()
</code></pre></div><p>这段程序的运行结果是什么？</p>
<p>从程序的分析来看，变量 <code>t</code> 并没有初始化，只是声明了类型。然后就直接调用了 <code>Hello</code> 方法，像是 nil 调用函数，理论上应该出现恐慌（panic）。</p>
<p>运行结果是：</p>
<pre><code>panic: runtime error: invalid memory address or nil pointer dereference
</code></pre><p>对不对呢？</p>
<p>显然，真正的运行结果是：</p>
<pre><code>脑子进煎鱼了
</code></pre><p>请你思考一下，想想这是为什么？</p>
<h2 id="为什么">为什么</h2>
<p>问题的原因是：很多小伙伴认为变量 <code>t</code> 的值都是 nil 了，不应该还能调用到才对。</p>
<p>更抽象化来讲，就是 ”程序是如何检查对象指针来寻找和调度所需函数“。</p>
<p>实际上，在 Go 中，表达式 <code>Expression.Name</code> 的语法，所调用的函数完全由 <code>Expression</code> 的类型决定。</p>
<p>其调用函数的指向不是由该表达式的特定运行时值来决定，包括我们前面所提到的 nil。</p>
<p>具体如下：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">func</span> (<span style="color:#a6e22e">p</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Sometype</span>) <span style="color:#a6e22e">Somemethod</span> (<span style="color:#a6e22e">firstArg</span> <span style="color:#66d9ef">int</span>) {}
</code></pre></div><p>本质上是：</p>
<div class="highlight"><pre style="color:#f8f8f2;background-color:#272822;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-golang" data-lang="golang"><span style="color:#66d9ef">func</span> <span style="color:#a6e22e">SometypeSomemethod</span>(<span style="color:#a6e22e">p</span> <span style="color:#f92672">*</span><span style="color:#a6e22e">Sometype</span>, <span style="color:#a6e22e">firstArg</span> <span style="color:#66d9ef">int</span>) {}
</code></pre></div><p>这么一看，其实大家应该都明白了。</p>
<p>上述入参 <code>p *Sometype</code> 是有具体上下文类型的，自然而然也就能调用到相应的方法。如果是没有任何上下文类型的，例如：<code>nil.Somemethod</code> 方法来调用，那肯定就是无法运行的。</p>
<p>与值是不是 nil，是什么，没有太多直接的影响。只要有预期类型的上下文就可以了。</p>
<h2 id="总结">总结</h2>
<p>今天给大家分享了一个 Go 语言里面的一个小细节，平时可能很多人没注意到，毕竟 IDE 也会标黄，会避开这个问题点。</p>
<p>在理解 Go 的设计和思考上，我们是需要清晰其背后的原因和逻辑的，也就是类型决定其调用，而不是值（容易误判）。</p>
<p>你有没有遇到过其它的细节问题呢，欢迎交流：）</p>


                                        
                                        
                                        
                                        <div class="rp4wp-related-posts">
                                            <h3>相关文章</h3>
                                            <ul>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/throw/">Go 有哪些无法恢复的致命场景？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/import-generics/">长达 12 年，Go 才引入泛型，是政治，还是技术问题？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/again-mutex/">Go 为什么不支持可重入锁？</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/switch-type/">Go 泛型玩出花，详解新提案 switch type！</a>
                                                    </div>
                                                </li>
                                                
                                                <li>
                                                    <div class="rp4wp-related-post-content">
                                                        <a
                                                            href="https://www.lican.site/posts/go/class-extends/">Go 为什么不支持类和继承？</a>
                                                    </div>
                                                </li>
                                                
                                            </ul>
                                        </div>
                                        
                                        
                                    </div>

                                    
                                    
                                    

                                    
                                    <div class="post-meta">
                                        
                                        
                                        <div class="post-tags">
                                            <ul>
                                            
                                            <li>
                                                <a href="/tags/go" title="View all posts tagged match">go</a>
                                            </li>
                                            
                                            </ul>
                                        </div>
                                        
                                        
                                        <nav class="further-reading">
                                            
                                            <div class="previous">
                                                <span>&lt;&lt; Prev</span>
                                                <a href="https://www.lican.site/posts/go/throw/"
                                                    rel="prev">Go 有哪些无法恢复的致命场景？</a> </div>
                                            
                                            
                                            <div class="next">
                                                <span>Next >></span>
                                                <a href="https://www.lican.site/posts/go/generics-design/">Go 泛型的 3 个核心设计，你学会了吗？</a> 
                                            </div>
                                            
                                        </nav>
                                    </div>
                                    
                                    

                                    
                                    
                                    

                                </div>
                            </article>
                        </div>
                    </div>
                </section>
                <aside class="sidebar sidebar-primary" id="sidebar-primary" role="complementary">
    <h1 class="screen-reader-text">Sidebar</h1>
    

    
    
    <section id="text-2" class="widget widget_text">
        <div class="textwidget">
            
            <div id="profile">
                <div id="profile_picture"><img src="https://www.lican.site/logo/logo.png"></div>
                <div id="profile_intro">
                    <p><span class="name">Lican</span></p>
                    <p class="intro">全栈开发者，爱好造轮子。</p>
                </div>
            </div>
            
            <p>
                <script type="text/javascript">
                    (function ($) {
                        $(document).ready(function () {
                            var menuPrimaryContainer = $('#menu-primary-container');
                            var profile = $('#text-2');
                            $('#toggle-navigation').click(function () {
                                if (menuPrimaryContainer.hasClass('open')) {
                                    profile.removeClass('open');
                                } else {
                                    profile.addClass('open');
                                }
                            });
                        });
                    })(jQuery);
                </script>
            </p>
        </div>
    </section>
    
    
    
    
    
    <section id="text-5" class="widget widget_text">
        <h2 class="widget-title">开源项目</h2>
        <div class="textwidget">
            <div id="projects" style="line-height: 22px;">
                
                <a href="https://github.com/idoubi/gonews"
                    target="_blank">gonews</a>: &nbsp;Daily news for golang<br>
                
                <a href="https://github.com/idoubi/sql2struct"
                    target="_blank">sql2struct</a>: &nbsp;Generate go struct according to SQL<br>
                
                <a href="https://github.com/idoubi/goz"
                    target="_blank">goz</a>: &nbsp;Request library used in golang<br>
                
        </div>
    </section>
    
    

    
    
    
    
    

    
    
    

    
    
    

    
    
    
    
</aside>
            </div>
        </div>

        <footer id="site-footer" class="site-footer" role="contentinfo">
    <div class="max-width">
    </div>
    <div class="footer">
        <div id="footercontent">
            © lican.vip All rights reserved<br/>
            Built with Hugo Theme <a href="https://github.com/idoubi/hugo-theme-period" target="_blank">Period</a>
        </div>
    </div>
</footer>

<script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?e8351b6d4626d5881d439ea1f6184baa";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
</script>
    
    
    </div>
    
</body>

</html>